<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
/**
 * 商品订单
 * @package app\erp\model
 */
class GoodsOrderlogic{

    /**
     * 首页
	 * params int 		user_id		// 操作用户id
	 * params int 		user_uid	// 下单用户id
	 * params int 		store_id	// 门店id
	 * params string 	order_code	// 订单号
	 * params int 		ps_type		// 配送方式 1 自提 2邮寄
	 * params int 		pay_status	// 支付状态 0待支付 1已支付(待出库) 5已支付(待提货) 2已完成(已提货) 3已取消 4已过期
	 * params int 		pay_type	// 支付方式 1 微信支付 2支付宝支付
     * @author shiqiang
     * @return array_out(code, message, data)
     */
    public function order_list($user_id, $user_uid = 0, $order_id = 0, $store_id = 0,$order_code = '', $ps_type = 0, $pay_status = '', $pay_type = 0){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 		=> $user_id,
				'user_uid' 		=> $user_uid,
				'order_id' 		=> $order_id,
				'store_id' 		=> $store_id,
				'order_code' 	=> $order_code,
				'ps_type' 		=> $ps_type,
				'pay_status' 	=> $pay_status,
				'pay_type' 		=> $pay_type,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $map = [];//搜索处理
			if($user_uid > 0) 		$map[] = ['uid', '=', $user_uid];
			if($order_id > 0)		$map[] = ['id', '=', $order_id];
//			if($store_id > 0)		$map[] = ['store_id', '=', $store_id];
			if($order_code != '')	$map[] = ['ordercode', '=', $order_code];
			if($ps_type > 0)		$map[] = ['ps_type', '=', $ps_type];
			if($pay_type > 0)		$map[] = ['pay_type', '=', $pay_type];
			
			if($pay_status >= 0 && $pay_status != ''){
				if($pay_status == 1){
					$map[] = ['pay_status', 'in', [1,5]]; // 已支付 1待出库 5待提货
				}else{
					$map[] = ['pay_status', '=', $pay_status];
				}
			}
			$map[] = ['pay_status', 'neq', 4];
			$map1 = $map2 = $map;
			$map1[] = ['pay_status', '>', 0];
			$map2[] = ['pay_status', '=', 0];
            $map2[] = ['pay_expiration_time', '>', time()];

			$list =  model('ErpGoodsOrder') -> whereOr([$map1,$map2]) -> order('pay_status desc, create_time desc') -> paginate();//获取列表
			
			$rel_list = [];
            foreach($list as $key => $value){
				$rel_list[$key] = $this -> order_details($value['id'], $user_uid);
			}
			
            $result_list = [];
            $result_list['total']  			= (int)$list -> total();//总数
            $result_list['current_page']	= (int)$list -> currentPage();//页码
            $result_list['last_page']   	= (int)$list -> lastPage();//总页数
            $result_list['per_page']   		= (int)$list -> listRows();//每页条数
            $result_list['data'] 			= $rel_list;
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}
	
	/**
     * 生成订单
	 * params int 		user_id		// 操作用户id
	 * params array 	sku_arr	// 产品信息
	 * params int 		store_id	// 门店id
	 * params array 	coupon_id	// 优惠卷id
     * @author baoshi
     * @return array_out(code, message, data)
     */
    public function order_create($user_id,  $store_id, $sku_arr, $coupon_info_id){
		DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 		=> $user_id,
				'store_id' 		=> $store_id,
				'sku_arr' 		=> $sku_arr,
				'coupon_info_id' 		=> $coupon_info_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $rel = $this -> createOrder($user_id, $store_id, $sku_arr, $coupon_info_id);
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

			/********逻辑返回********/
			if($rel['code'] == 200){
				DB::commit();
            	return array_out(200, 'success', $rel['data']);
			}else{
				DB::rollback();
				return array_out($rel['code'], $rel['message'], $rel['data']);
			}
			
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}

	/**
     * 生成订单(团购)
	 * params int 		user_id		// 操作用户id
	 * params array 	sku_arr	// 产品信息
	 * params int 		store_id	// 门店id
	 * params array 	coupon_id	// 优惠卷id
     * @author baoshi
     * @return array_out(code, message, data)
     */
    public function order_create_tuan($user_id,  $store_id, $sku_arr, $coupon_info_id){
		DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 		=> $user_id,
				'store_id' 		=> $store_id,
				'sku_arr' 		=> $sku_arr,
				'coupon_info_id' 		=> $coupon_info_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $rel = $this -> createOrderTuan($user_id, $store_id, $sku_arr, $coupon_info_id);
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

			/********逻辑返回********/
			if($rel['code'] == 200){
				DB::commit();
            	return array_out(200, 'success', $rel['data']);
			}else{
				DB::rollback();
				return array_out($rel['code'], $rel['message'], $rel['data']);
			}
			
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}
	
	/**
     * 订单支付
	 * params int 		user_id		// 操作用户id
	 * params int 		pay_type	// 支付方式
	 * params int 		order_id	// 订单id
     * @author baoshi
     * @return array_out(code, message, data)
     */
    public function order_pay($user_id, $pay_type, $order_id){
		DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 		=> $user_id,
				'pay_type' 		=> $pay_type,
				'order_id' 		=> $order_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

			/********业务逻辑********/
			//判断订单是否有效
			$orderobj = model('ErpGoodsOrder') -> find($order_id);
			if(!$orderobj || $orderobj -> pay_status != 0) return array_out('-1002', '订单无效');

			switch ($pay_type) {
				case 1://微信支付
					$rel = $this -> wechatPay($user_id, $order_id);
					break;
				case 2://支付宝支付
					//$rel =  $this -> buyVipByAlipay($user_id, $order_id);
					break;
				case 3://现金支付
					//$rel = $this -> xianjinPay($user_id, $order_id);
					$rel['code'] = 200;
					$rel['data'] = '请在30分钟内完成现金付款，否则订单失效！';
					break;
				case 4://余额支付
					
					$rel = $this -> balancePay($user_id, $order_id);
					break;
				default:
					return array_out('-9999', '支付类型无效');
					break;
			}

			//更新订单支付方式 
			$map = [];
			$map['id'] = $order_id;
			
			$rel1 = model('ErpGoodsOrder') -> where($map) -> setField('pay_type', $pay_type);
            //$rel = $this -> payOrder($user_id, $pay_type, $order_id);
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

			/********逻辑返回********/
			if($rel['code'] == 200){
				DB::commit();
            	return array_out(200, 'success', $rel['data']);
			}else{
				DB::rollback();
				return array_out($rel['code'], $rel['message'], $rel['data']);
			}
			
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}


	/**
     * 下单
	 * params int 		user_id		// 操作用户id
	 * params array 	sku_arr	// 产品信息
	 * params int 		store_id	// 门店id
	 * params int 		pay_type	// 支付方式 1 微信支付 2支付宝支付
     * @author baoshi
     * @return array_out(code, message, data)
     */
    public function order_buy($user_id, $pay_type, $store_id, $sku_arr){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 		=> $user_id,
				'store_id' 		=> $store_id,
				'sku_arr' 		=> $sku_arr,
				'pay_type' 		=> $pay_type,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            switch ($pay_type) {
				case 1://微信支付
					$rel = $this -> buyVipByWechatpay($user_id, $store_id, $sku_arr);
					break;
				case 2://支付宝支付
					$rel =  $this -> buyVipByAlipay($user_id, $store_id, $sku_arr);
					break;
				default:
					return array_out('-9999', '支付类型无效');
					break;
			}
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

			/********逻辑返回********/
			if($rel['code'] == 200){
				DB::commit();
            	return array_out(200, 'success', $rel['data']);
			}else{
				DB::rollback();
				return array_out($rel['code'], $rel['message'], $rel['data']);
			}
			
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}
	
	/**
     * 微信支付 购买VIP
     * @param int $timeType  购买期限 0年 1月 2永久
     * @param int $num       购买数量（年和月有效）
     * @return array
     */
    private function buyVipByWechatpay($user_id, $store_id, $sku_arr){
		$pay_price = 0;
		foreach ($sku_arr as $key => $value) {
			if(!isset($value['sku_id']) || !isset($value['num']) ) return array_out(-1001, 'sku_arr格式错误');//后置错误 -1003
			$rel = controller('GoodsWarehouseStockNumlogic', 'logic') -> getKucunNum($store_id, $value['sku_id']);
			if($rel['code'] != 200){
				// return array_out(-1001, '订单中存在该商店无货商品,skuid:'.$value['sku_id']);//后置错误 -1003
				return array_out(-1001, '所选商品当前门店无货');//后置错误 -1003
			}

			//判断库存是否充足
			if($rel['data']['available_num'] < $value['num']){
				// return array_out(-1002, '订单中存在该商店库存不足商品,skuid:'.$value['sku_id']);//后置错误 -1003
				return array_out(-1002, '所选商品当前门店无货');//后置错误 -1003
			}

			//判断库存是否充足
			if($rel['data']['sku_status'] != 1){
				// return array_out(-1002, '订单中存在该商店库存不足商品,skuid:'.$value['sku_id']);//后置错误 -1003
				return array_out(-1002, '订单中存在下架商品');//后置错误 -1003
			}
			
			$sku_list[] = [
				'sku_id' => $value['sku_id'],
				'num' 	 => $value['num'],
				'price'  => $rel['data']['price'],
				//'id' 	 => $value['id'],
			];

			$pay_price = $pay_price + $rel['data']['price']*$value['num'];
			//下单 减去购物车这个skuid
			if(isset($value['id'])){
				model('ErpGoodsSalecar') -> destroy($value['id']);
			}
			
			//下单 减去库存
			$map = [];
			$map['sku_id'] = $value['sku_id'];
			$map['warehouse_id'] = $rel['data']['warehouse_id'];
			$data = [];
			$data['available_num'] = $rel['data']['available_num'] - $value['num'];//可操作数减少
			$data['frozen_num']    = $rel['data']['frozen_num'] + $value['num'];//冻结数增加
			$rel1 = model('ErpGoodsWarehouseStockNum') -> save($data, $map);
			//查询当前库存是否充足
			$rel2 = controller('GoodsWarehouseStockNumlogic', 'logic') -> getKucunNum($store_id, $value['sku_id']);
			if($rel2['code'] != 200  || $rel2['data']['available_num'] < 0){
				return array_out(-1002, '订单中存在该商店库存不足商品,skuid:'.$value['sku_id']);//后置错误 -1003
			}
			//dump($rel1);dump($rel2);dump($sku_list);
		}
		
		//生成订单
		$ordercode = date('YmdHis', time()).rand(100000,999999);
		$uid = $user_id;
		$pay_type = 1;
		$pay_orderid = '';
		//$pay_price = $pay_price;
		$pay_price = 0.01;
		$store_id = $store_id;
		$rel3 = model('ErpGoodsOrder') -> addData($ordercode, $uid, $pay_type, $pay_orderid, $pay_price, $store_id, $ps_type = 1, $pay_status =0);
		if($rel3['code'] != 200) array_out(-1003, '订单生成失败');//后置错误 -1003

		//订单单品详情
		foreach ($sku_list as $key => $value) {
			$orderskulist[] = [
				'sku_id' 	=> $value['sku_id'],
				'num' 	 	=> $value['num'],
				'price'  	=> $value['price'],
				'order_id'  => $rel3['data'],
			];
		}//dump($orderskulist);die;
		$rel4 = model('ErpGoodsOrderSkulist') -> saveAll($orderskulist);

		//微信支付
		$body = "支付订单号：".$ordercode;
		$rel5 = factory('PayFactory', 'pay') -> getInstance($type = 'Wechat') -> getPrePayOrder($body, $out_trade_no = $ordercode, $total_fee = $pay_price*100, $notify_url = $_SERVER['HTTP_HOST'].url('publics/notify'));
		if($rel5['return_code'] != 'SUCCESS') array_out(-1001, '订单生成失败');
		//dump($ordercode);dump($rel5);
		$data = [];
		$data['appid'] = $rel5['appid'];

		$transferPayment_rel = factory('PayFactory', 'pay') -> getInstance($type = 'Wechat') -> transferPayment($rel5['prepay_id']);
		$transferPayment_rel['payType'] = 0;
		$transferPayment_rel['orderId'] = $rel3['data'];
		Cache::set('order_wechatpay_'.$rel3['data'], $transferPayment_rel, 60*60*24);
		//dump($transferPayment_rel);
		return array_out(200, '生成预付款订单成功', $transferPayment_rel);

	}

	/**
     * 微信支付
     * @param int $user_id  用户id
     * @param int $order_id       订单id
     * @return array
     */
    private function wechatPay($user_id, $order_id){
		$rel = model('ErpGoodsOrder') -> find($order_id);
		if(!$rel) return array_out(-1001, '订单id无效');

		$ordercode = $rel['ordercode'];
		//$pay_price = $rel['pay_price'];
		//$pay_price = 0.01;
		if(config('develop_mode') == 1){
			$pay_price = 0.01;
		}else{
			$pay_price = $rel['pay_price'];
		}
		//微信支付
		$body = "支付订单号：".$ordercode;
		$rel5 = factory('PayFactory', 'pay') -> getInstance($type = 'Wechat') -> getPrePayOrder($body, $out_trade_no = $ordercode, $total_fee = $pay_price*100, $notify_url = $_SERVER['HTTP_HOST'].url('publics/notify'));
		if($rel5['return_code'] != 'SUCCESS' || $rel5['result_code'] != 'SUCCESS') return array_out(-1001, '订单生成失败');

		$data = [];
		$data['appid'] = $rel5['appid'];

		$transferPayment_rel = factory('PayFactory', 'pay') -> getInstance($type = 'Wechat') -> transferPayment($rel5['prepay_id']);
		$transferPayment_rel['payType'] = 0;
		$transferPayment_rel['orderId'] = $order_id;
		Cache::set('order_wechatpay_'.$order_id, $transferPayment_rel, 60*60*24);
		//dump($transferPayment_rel);
		return array_out(200, '生成预付款订单成功', $transferPayment_rel);
	}

	/**
     * 余额付
     * @param int $user_id  用户id
     * @param int $order_id       订单id
     * @return array
     */
    private function balancePay($user_id, $order_id){
		$rel = model('ErpGoodsOrder') -> find($order_id);
		if(!$rel) return array_out(-1001, '订单id无效');
		$order_type = $rel['order_type'];

		$ordercode = $rel['ordercode'];
		$pay_price = $rel['pay_price'];

		//余额支付
		//$map = [];
		//$map['uid'] = $user_id;
		//$res2 = model('user_center/UcMemberBalanceJournalLog', 'model\user') -> where($map) -> setDec('balance', $pay_price);
		$rel2 = model('user_center/UcMemberBalanceJournalLog', 'model\user') -> addData($user_id, $journal_id = $order_id, $ine = 3, $pay_price, $use_rule ='', $log_remark='消费');
		if($rel2['code'] != 200) return array_out(-1001, '付款失败');

		$map = [];
		$map['uid'] = $user_id;
		$res3 = model('user_center/Member', 'model\user') -> where($map) -> find();
		$balance = $res3 -> balance;//余额
		if($balance < 0) return array_out(-1001, '余额不足！');
		
		//库存扣除
		$store_id = $rel -> store_id;
		//先  取出 门店对应的仓库 id
		$warehouse_list = model('erp/ErpStoreWarehouse') -> getStoreWarehouse($store_id);
		foreach ($warehouse_list['data'] as $key => $value) {
			if($value['type'] == 1){//分店仓库
				$store_warehouse_list = $value['wid'];
			}
		}

		foreach ($rel -> get_goods_order_skulist as $key => $value) {
			$map = [];
			$map['sku_id'] = $value['sku_id'];
			$map['warehouse_id'] = $store_warehouse_list;
			model('ErpGoodsWarehouseStockNum') ->where($map) -> setDec('frozen_num', $value['num']);//冻结减去
			model('ErpGoodsWarehouseStockNum') ->where($map) -> setDec('stock_num', $value['num']);//总库存减去

			//判断是否是团购订单
			if($order_type ==1){
				$map = [];
				$map['id'] = $value['sponsor_id'];
				model('ErpGroupSponsorSku') ->where($map) -> setDec('dj_num', $value['num']);//冻结减去
			}
		}

		//更新订单信息
		$map = [];
		$map['id'] = $order_id;

		$data = [];
		$data['payover_time'] = time();
		$data['pay_status'] = 1;
		
		$rel = model('ErpGoodsOrder') -> save($data, $map);
		if(!$rel) return array_out(-1001, '订单更新失败');
		//dump($transferPayment_rel);
		
		//添加一个行为
		$params = [];
		$params['order_id'] = $order_id;
		$hook_rel = Hook::listen('order_over_after',$params);
		return array_out(200, '付款成功');
	}

	/**
     * 生成订单
     * @return array
     */
    private function createOrder($user_id, $store_id, $sku_arr, $coupon_info_id){
		$pay_price = 0;
		foreach ($sku_arr as $key => $value) {
			if(!isset($value['sku_id']) || !isset($value['num']) ) return array_out(-1001, 'sku_arr格式错误');//后置错误 -1003
			$rel = controller('GoodsWarehouseStockNumlogic', 'logic') -> getKucunNum($store_id, $value['sku_id']);
			if($rel['code'] != 200){
				// return array_out(-1001, '订单中存在该商店无货商品,skuid:'.$value['sku_id']);//后置错误 -1003
				return array_out(-1001, '所选商品当前门店无货');//后置错误 -1003
			}

			//判断库存是否充足
			if($rel['data']['available_num'] < $value['num']){
				// return array_out(-1002, '订单中存在该商店库存不足商品,skuid:'.$value['sku_id']);//后置错误 -1003
				return array_out(-1002, '所选商品当前门店无货');//后置错误 -1003
			}

			//判断库存是否充足
			if($rel['data']['sku_status'] != 1){
				// return array_out(-1002, '订单中存在该商店库存不足商品,skuid:'.$value['sku_id']);//后置错误 -1003
				return array_out(-1002, '订单中存在下架商品');//后置错误 -1003
			}
			
			$sku_list[] = [
				'sku_id' => $value['sku_id'],
				'num' 	 => $value['num'],
				'price'  => $rel['data']['price'],
				//'id' 	 => $value['id'],
			];

			$pay_price = $pay_price + $rel['data']['price']*$value['num'];
			//下单 减去购物车这个skuid
			if(isset($value['id'])){
				model('ErpGoodsSalecar') -> destroy($value['id']);
			}
			
			//下单 减去库存
			$map = [];
			$map['sku_id'] = $value['sku_id'];
			$map['warehouse_id'] = $rel['data']['warehouse_id'];
			$data = [];
			$data['available_num'] = $rel['data']['available_num'] - $value['num'];//可操作数减少
			$data['frozen_num']    = $rel['data']['frozen_num'] + $value['num'];//冻结数增加
			$rel1 = model('ErpGoodsWarehouseStockNum') -> update($data, $map);

			//$body = json_encode($bodyinput, true);
			
			//查询当前库存是否充足
			$rel2 = controller('GoodsWarehouseStockNumlogic', 'logic') -> getKucunNum($store_id, $value['sku_id']);
			if(!$rel1 || $rel2['code'] != 200  || $rel2['data']['available_num'] < 0){
				return array_out(-1002, '订单中存在该商店库存不足商品,skuid:'.$value['sku_id']);//后置错误 -1003
			}
			//dump($rel1);dump($rel2);dump($sku_list);
		}

		$ordercode = date('YmdHis', time()).rand(100000,999999);

		//判断 优惠卷
		if($coupon_info_id > 0){
			$map = [];
			$map[] = ['coupon_status', '=', 0];
			$map[] = ['coupon_user', '=', $user_id];
			$map[] = ['coupon_use_type', '=', 0];
			//$map[] = ['coupon_stime', '<', time()];
			//$map[] = ['coupon_etime', '>', time()];
			$rel = model('ErpCouponUseinfo') -> where($map) -> find();

			if(isset($rel) && $rel->get_erp_coupon->coupon_use_condition == 1){//有条件 1是满减
				if($pay_price >= $rel->get_erp_coupon->coupon_use_condition_num){//满减优惠券金额
					$pay_price = $pay_price - $rel->get_erp_coupon->coupon_value;
					//更新优惠卷使用状态
					$map = [];
					$map['id'] = $rel->id;
					$data = [];
					$data['coupon_usetime'] = time();
					$data['coupon_ordercode'] = $ordercode;
					$data['coupon_use_type'] = 2;
					model('ErpCouponUseinfo') -> update($data, $map);//dump($pay_price);
				}
			}else if(isset($rel) && $rel->get_erp_coupon->coupon_use_condition == 0){//无条件
				if($pay_price >= $rel->get_erp_coupon->coupon_value){//满减优惠券金额
					$pay_price = $pay_price - $rel->get_erp_coupon->coupon_value;
					//更新优惠卷使用状态
					$map = [];
					$map['id'] = $rel->id;
					$data = [];
					$data['coupon_usetime'] = time();
					$data['coupon_ordercode'] = $ordercode;
					$data['coupon_use_type'] = 2;
					model('ErpCouponUseinfo') -> update($data, $map);//dump($pay_price);
				}
			}
		}
		//dump($coupon_info_id);die;
		//生成订单
		
		$uid = $user_id;
		$pay_type = 0;
		$pay_orderid = '';
		$pay_price = $pay_price;
		//$pay_price = 0.01;//临时
		$store_id = $store_id;
		$rel3 = model('ErpGoodsOrder') -> addData($ordercode, $uid, $pay_type, $pay_orderid, $pay_price, $store_id, $ps_type = 1, $pay_status =0);
		if($rel3['code'] != 200) array_out(-1003, '订单生成失败');//后置错误 -1003

		//订单单品详情
		foreach ($sku_list as $key => $value) {
			$orderskulist[] = [
				'sku_id' 	=> $value['sku_id'],
				'num' 	 	=> $value['num'],
				'price'  	=> $value['price'],
				'order_id'  => $rel3['data'],
			];
		}//dump($orderskulist);die;
		$rel4 = model('ErpGoodsOrderSkulist') -> saveAll($orderskulist);
		$transferPayment_rel['orderId'] = $rel3['data'];

		//微信支付
		/*$body = "支付订单号：".$ordercode;
		$rel5 = factory('PayFactory', 'pay') -> getInstance($type = 'Wechat') -> getPrePayOrder($body, $out_trade_no = $ordercode, $total_fee = $pay_price*100, $notify_url = $_SERVER['SERVER_NAME'].url('publics/notify'));
		if($rel5['return_code'] != 'SUCCESS') array_out(-1001, '订单生成失败');
		//dump($ordercode);dump($rel5);
		$data = [];
		$data['appid'] = $rel5['appid'];

		$transferPayment_rel = factory('PayFactory', 'pay') -> getInstance($type = 'Wechat') -> transferPayment($rel5['prepay_id']);
		$transferPayment_rel['payType'] = 0;
		$transferPayment_rel['orderId'] = $rel3['data'];
		Cache::set('order_wechatpay_'.$rel3['data'], $transferPayment_rel, 60*60*24);*/
		//dump($transferPayment_rel);
		return array_out(200, '生成预付款订单成功', $transferPayment_rel);

	}

	/**
     * 生成订单(团购)
     * @return array
     */
    private function createOrderTuan($user_id, $store_id, $sku_arr, $coupon_info_id){
		$pay_price = 0;
		foreach ($sku_arr as $key => $value) {
			if(!isset($value['sponsor_id']) || !isset($value['num'])) return array_out(-1001, 'sku_arr格式错误');//后置错误 -1003
			/*判断团购商品是否有货*/
			
			//1 判断团购剩余数量
			$map = [];
			$map[] = ['id', '=', $value['sponsor_id']];
			$map[] = ['store_id', 'in', [0,$store_id]];
			$sponsor_rel = model('ErpGroupSponsorSku') -> where($map) -> find();//dump($sponsor_rel);
			if(!$sponsor_rel) return array_out(-1001, '团购无效');//后置错误 -1003
			
			//2 下单 减去库存
			$map = [];
			$map[] = ['id', '=', $value['sponsor_id']];
			$map[] = ['store_id', 'in', [0,$store_id]];
			$rel1 = model('ErpGroupSponsorSku') ->where($map) -> setDec('ksy_num', $value['num']);//可用减少
			$rel2 = model('ErpGroupSponsorSku') ->where($map) -> setInc('dj_num', $value['num']);//冻结增加

			//3查询库存是否足够
			$map = [];
			$map[] = ['id', '=', $value['sponsor_id']];
			$map[] = ['store_id', 'in', [0, $store_id]];
			$sponsor_rel = model('ErpGroupSponsorSku') -> where($map) -> find();
			$group_price = $sponsor_rel -> show_price;
			if($sponsor_rel['ksy_num'] < 0) return array_out(-1002, '已经抢光啦~');//后置错误 -1003
			
			//4团购是否正在进行
			if($sponsor_rel->get_erp_group_sponsor->tg_start_time > time() ){
				return array_out(-1002, '团购尚未开始~');//后置错误 -1003
			}
			if( $sponsor_rel->get_erp_group_sponsor->tg_end_time < time()){
				return array_out(-1002, '团购已结束~');//后置错误 -1003
			}
			//团购是否已经禁用
			if( $sponsor_rel->get_erp_group_sponsor->tg_status == 0){
				return array_out(-1002, '团购已禁用~');//后置错误 -1003
			}

			

			/*判断商品是否有货*/
			$rel = controller('GoodsWarehouseStockNumlogic', 'logic') -> getKucunNum($store_id, $sponsor_rel->sku_id);
			if($rel['code'] != 200){
				// return array_out(-1001, '订单中存在该商店无货商品,skuid:'.$value['sku_id']);//后置错误 -1003
				return array_out(-1001, '所选商品当前门店无货');//后置错误 -1003
			}

			//判断库存是否充足
			if($rel['data']['available_num'] < $value['num']){
				// return array_out(-1002, '订单中存在该商店库存不足商品,skuid:'.$value['sku_id']);//后置错误 -1003
				return array_out(-1002, '所选商品当前门店无货');//后置错误 -1003
			}

			//判断库存是否充足
			if($rel['data']['sku_status'] != 1){
				// return array_out(-1002, '订单中存在该商店库存不足商品,skuid:'.$value['sku_id']);//后置错误 -1003
				return array_out(-1002, '订单中存在下架商品');//后置错误 -1003
			}
			
			$sku_list[] = [
				'sku_id' => $sponsor_rel->sku_id,
				'num' 	 => $value['num'],
				'price'  => $group_price,
				'sponsor_id' 	 => $value['sponsor_id'],
			];

			$pay_price = $pay_price + $group_price*$value['num'];
			//下单 减去购物车这个skuid
			if(isset($value['id'])){
				//model('ErpGoodsSalecar') -> destroy($value['id']);
			}
			
			//下单 减去库存
			$map = [];
			$map['sku_id'] = $sponsor_rel->sku_id;
			$map['warehouse_id'] = $rel['data']['warehouse_id'];
			$data = [];
			$data['available_num'] = $rel['data']['available_num'] - $value['num'];//可操作数减少
			$data['frozen_num']    = $rel['data']['frozen_num'] + $value['num'];//冻结数增加
			$rel1 = model('ErpGoodsWarehouseStockNum') -> update($data, $map);

			//$body = json_encode($bodyinput, true);
			
			//查询当前库存是否充足
			$rel2 = controller('GoodsWarehouseStockNumlogic', 'logic') -> getKucunNum($store_id, $sponsor_rel->sku_id);
			if(!$rel1 || $rel2['code'] != 200  || $rel2['data']['available_num'] < 0){
				return array_out(-1002, '订单中存在该商店库存不足商品,skuid:'.$sponsor_rel->sku_id);//后置错误 -1003
			}
			//dump($rel1);dump($rel2);dump($sku_list);
		}

		$ordercode = date('YmdHis', time()).rand(100000,999999);

		//判断 优惠卷
		if($coupon_info_id > 0){
			$map = [];
			$map[] = ['coupon_status', '=', 0];
			$map[] = ['coupon_user', '=', $user_id];
			$map[] = ['coupon_use_type', '=', 0];
			//$map[] = ['coupon_stime', '<', time()];
			//$map[] = ['coupon_etime', '>', time()];
			$rel = model('ErpCouponUseinfo') -> where($map) -> find();

			if(isset($rel) && $rel->get_erp_coupon->coupon_use_condition == 1){//有条件 1是满减
				if($pay_price >= $rel->get_erp_coupon->coupon_use_condition_num){//满减优惠券金额
					$pay_price = $pay_price - $rel->get_erp_coupon->coupon_value;
					//更新优惠卷使用状态
					$map = [];
					$map['id'] = $rel->id;
					$data = [];
					$data['coupon_usetime'] = time();
					$data['coupon_ordercode'] = $ordercode;
					$data['coupon_use_type'] = 2;
					model('ErpCouponUseinfo') -> update($data, $map);//dump($pay_price);
				}
			}else if(isset($rel) && $rel->get_erp_coupon->coupon_use_condition == 0){//无条件
				if($pay_price >= $rel->get_erp_coupon->coupon_value){//满减优惠券金额
					$pay_price = $pay_price - $rel->get_erp_coupon->coupon_value;
					//更新优惠卷使用状态
					$map = [];
					$map['id'] = $rel->id;
					$data = [];
					$data['coupon_usetime'] = time();
					$data['coupon_ordercode'] = $ordercode;
					$data['coupon_use_type'] = 2;
					model('ErpCouponUseinfo') -> update($data, $map);//dump($pay_price);
				}
			}
		}
		//dump($coupon_info_id);die;
		//生成订单
		
		$uid = $user_id;
		$pay_type = 0;
		$pay_orderid = '';
		$pay_price = $pay_price;
		//$pay_price = 0.01;//临时
		$store_id = $store_id;
		$rel3 = model('ErpGoodsOrder') -> addData($ordercode, $uid, $pay_type, $pay_orderid, $pay_price, $store_id, $ps_type = 1, $pay_status =0, $order_type =1);
		if($rel3['code'] != 200) array_out(-1003, '订单生成失败');//后置错误 -1003

		//订单单品详情
		foreach ($sku_list as $key => $value) {
			$orderskulist[] = [
				'sku_id' 	=> $value['sku_id'],
				'num' 	 	=> $value['num'],
				'price'  	=> $value['price'],
				'order_id'  => $rel3['data'],
				'sponsor_id' 	 => $value['sponsor_id'],
			];
		}//dump($orderskulist);die;
		$rel4 = model('ErpGoodsOrderSkulist') -> saveAll($orderskulist);
		$transferPayment_rel['orderId'] = $rel3['data'];

		//微信支付
		/*$body = "支付订单号：".$ordercode;
		$rel5 = factory('PayFactory', 'pay') -> getInstance($type = 'Wechat') -> getPrePayOrder($body, $out_trade_no = $ordercode, $total_fee = $pay_price*100, $notify_url = $_SERVER['SERVER_NAME'].url('publics/notify'));
		if($rel5['return_code'] != 'SUCCESS') array_out(-1001, '订单生成失败');
		//dump($ordercode);dump($rel5);
		$data = [];
		$data['appid'] = $rel5['appid'];

		$transferPayment_rel = factory('PayFactory', 'pay') -> getInstance($type = 'Wechat') -> transferPayment($rel5['prepay_id']);
		$transferPayment_rel['payType'] = 0;
		$transferPayment_rel['orderId'] = $rel3['data'];
		Cache::set('order_wechatpay_'.$rel3['data'], $transferPayment_rel, 60*60*24);*/
		//dump($transferPayment_rel);
		return array_out(200, '生成预付款订单成功', $transferPayment_rel);

	}
	
	
	
	/**
     * 取消订单
	 * params int 		user_id		// 操作用户id
	 * params int 		user_uid	// 下单用户id
	 * params int 		order_id	// 订单id
	 * params int 		store_id	// 门店id
     * @author shiqiang
     * @return array_out(code, message, data)
     */
    public function order_cancel($user_id, $user_uid, $order_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 		=> $user_id,
				'user_uid' 		=> $user_uid,
				'order_id' 		=> $order_id,
				//'store_id' 		=> $store_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			//取消订单
			$map = [];
			$map['uid'] 		= $user_id;
			$map['id'] 			= $order_id;
			// $map['store_id'] 	= $store_id;
			
			$data = [];
			$data['pay_status'] = 3;
			
			$res = model('ErpGoodsOrder') -> update($data, $map);
			if(!$res){
				DB::rollback();
				return array_out(-1005, 'error');//取消失败
			}
			//查询订单号
			$order_info = model('ErpGoodsOrder') -> find($order_id);
			
			$order_type = $order_info['order_type'];
			$store_id   = $order_info['store_id'];
			//释放优惠券
			$ordercode = $order_info['ordercode'];
			$map = [];
			$map['coupon_ordercode'] = $ordercode;
			$coupon_user = model('ErpCouponUseinfo') -> where($map) -> column('id');//当前订单使用的优惠券
			if(!empty($coupon_user)){
				foreach($coupon_user as $coupon_id){
					$map = [];
					$map['id'] = $coupon_id;
					
					$data = [];
					$data['coupon_ordercode'] = 0;
					$data['coupon_usetime'] = '';
					$data['coupon_use_type'] = 0;
					$rel = model('ErpCouponUseinfo')->update($data, $map);
					if(!$rel){
						DB::rollback();
						return array_out(-1005, 'error4');//退优惠券失败
					}
				}
			}
			
			$map = [];
			$map['order_id'] = $order_id;
			//释放库存
			$sku_list = model('ErpGoodsOrderSkulist') -> where($map) -> column('id,sku_id,num,sponsor_id');
			
			//根据门店id 查询出仓库的id
			$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($store_id);
			foreach ($warehouse_list['data'] as $key => $value) {
				if($value['type'] == 1){//分店仓库
					$store_warehouse_list[] = $value['wid'];
				}
			}
			$warehouse_id 	= $store_warehouse_list[0];//仓库id
			
			foreach($sku_list as $key => $value){
				$sku_id = $value['sku_id'];
				$num 	= $value['num'];
	
				$map = [];
				$map['sku_id'] 			= $sku_id;
				$map['warehouse_id'] 	= $warehouse_id;
				$sku_info = model('ErpGoodsWarehouseStockNum') -> where($map) -> find();//当前库存

				//计算库存数
				$frozen_num 	= $sku_info['frozen_num'] - $num; //冻结数 减少
				$available_num 	= $sku_info['available_num'] + $num; //可用库存增加
				$stock_num = $frozen_num + $available_num; //总库存
				//插入库存
				$map = [];
				$map['id'] = $sku_info['id'];
				$map['warehouse_id'] = $warehouse_id;
				
				$data= [];
				$data['frozen_num'] 	= $frozen_num;
				$data['available_num'] 	= $available_num;
				$data['stock_num'] 		= $stock_num;
				
				$res = model('ErpGoodsWarehouseStockNum') -> update($data, $map);

				//判断是否是团购订单
				if($order_type ==1){
					$map = [];
					$map['id'] = $value['sponsor_id'];
					model('ErpGroupSponsorSku') ->where($map) -> setDec('dj_num', $value['num']);//冻结减去
					model('ErpGroupSponsorSku') ->where($map) -> setInc('ksy_num', $value['num']);//可用减去
				}

				if(!$res){
					DB::rollback();
					return array_out(-1005, 'error2');//库存修改失败
				}
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}
	
	/**
     * 用户提货 - 订单完成
	 * params int 		user_id		// 操作用户id
	 * params int 		user_uid	// 下单用户id
	 * params int 		order_id	// 订单id
	 * params int 		store_id	// 门店id
     * @author shiqiang
     * @return array_out(code, message, data)
     */
    public function order_complete($user_id, $order_id, $store_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 		=> $user_id,
				'order_id' 		=> $order_id,
				'store_id' 		=> $store_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			//订单完成
			$map = [];
			$map['uid'] 		= $user_id;
			$map['id'] 			= $order_id;
			// $map['store_id'] 	= $store_id;

			$data = [];
			$data['pay_status'] = 2;
	
			$res = model('ErpGoodsOrder') -> save($data, $map);
			if(!$res){
				DB::rollback();
				return array_out(-1005, 'error');//提货成功
			}
			$order_details = $this -> order_details($order_id, $user_id);
			//门店相关
			$store_title = model('ErpStore') -> find($order_details['stroeId']) -> title;
			$order_details['store_title'] = $store_title;
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $order_details);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}
	
	
	/**
     * 删除订单
	 * params int 		user_id		// 操作用户id
	 * params int 		order_id	// 订单id
	 * params int 		store_id	// 门店id
     * @author shiqiang
     * @return array_out(code, message, data)
     */
    public function order_delete($user_id, $order_id, $store_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 		=> $user_id,
				'order_id' 		=> $order_id,
				'store_id' 		=> $store_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			//订单删除
			$rel = model('ErpGoodsOrder') -> deleteData($user_id, $order_id);
			if($rel['code'] < 200){
				DB::rollback();
                return array_out(-1005, 'error');
			}
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}
	
	/**
     * 订单详情
	 * params int 		user_id		// 操作用户id
	 * params array 	sku_arr	// 产品信息
	 * params int 		store_id	// 门店id
	*/
	public function order_details($order_id = '', $user_uid){
		$info =  model('ErpGoodsOrder') -> find($order_id);
		// $map = [];
		// $map['order_id'] = $info['id'];
		// $evaluate = model('ErpEvaluate') -> where($map) -> find();//获取列表
		// if(!empty($evaluate)){
			// $evaluate_type = 1;
		// }else{
			// $evaluate_type = 0;
		// }
        $store_title = model('ErpStore') -> find($info['store_id']) -> title;

		$rel_list = [];
		//订单相关
		$rel_list['orderId'] 			= (int)$info['id'];
		$rel_list['ordercode'] 			= (string)$info['ordercode'];
		$rel_list['payType'] 			= (int)$info['pay_type'];
		$rel_list['payStatus'] 			= (int)$info['pay_status'];
		$rel_list['payOrderid'] 		= (string)$info['pay_orderid'];
		$rel_list['payPrice'] 			= (string)$info['pay_price'];
		$rel_list['payExpirationTime'] 	= (int)$info['pay_expiration_time']; //订单过期时间
		$rel_list['stroeId'] 			= (int)$info['store_id'];
		$rel_list['storeTitle'] 		= (string)$store_title;
		$rel_list['psType'] 			= (int)$info['ps_type'];
		$rel_list['createTime'] 		= (int)$info['create_time']; //订单过期时间
		$rel_list['updateTime'] 		= (int)$info['update_time'];
		// $rel_list['evaluateType'] 		= (int)$evaluate_type; //是否评价
		
		//用户相关
		$userinfo = controller('user_center/Userlogic', 'logic\user') -> get_user_info($user_uid, $user_uid); //用户详情
		$rel_list['userInfo'] = $userinfo['data'];

		//支付相关
		$rel_list['wechatPay'] = Cache::get('order_wechatpay_'.$info['id']);
		
		//sku相关
		$sku_list = $info -> get_goods_order_skulist;
		$sku_arr = [];
		foreach($sku_list as $val){
			$goods_sku = controller('GoodsSkulogic', 'logic') -> goods_sku_info_skuid($user_uid, $val['sku_id'], $info['store_id']);//商品详情
			$map = [];
			$map['goods_id'] = $goods_sku['data']['goodsInfo']['goodsId'];
			$map['order_id'] = $info['id'];
			$map['sku_id']   = $val['sku_id'];
			$evaluate = model('ErpEvaluate') -> where($map) -> find();//获取列表
			if(!empty($evaluate)){
				$evaluate_type = 1;
			}else{
				$evaluate_type = 0;
			}
			
			$sku_arr[] = [
				'price' 		=> (string)$val['price'],
				'num' 			=> (int)$val['num'],
				'goodsSkuInfo' 	=> (array)$goods_sku['data'],
				'evaluateType'  => (int)$evaluate_type, //是否评价
			];
		}
		$rel_list['orderGoods'] = $sku_arr;
		return $rel_list;
	}
	
	 /* 订单过期
     * @author shqiang
	 * @return json_out(code, message, data)
	*/
	public function order_expire(){
		DB::startTrans();//启动事务
		try{
			$map = [];
			$map[] = ['pay_status', '=', '0'];//已过期
			$map[] = ['pay_expiration_time', '<', time()];//已过期
			$order_list = model('ErpGoodsOrder') -> where($map) -> column('id,store_id,ordercode, order_type');//已过期的订单
			
			if(!empty($order_list)){
				foreach($order_list as $value){
					$order_id = $value['id'];
					$order_type = $value['order_type'];
					//变更订单状态
					$map = [];
					$map['id'] = $order_id;
					$data = [];
					$data['pay_status'] = 4;
					$rel = model('ErpGoodsOrder') -> update($data, $map);
					if(!$rel){
						DB::rollback();
						return array_out(-1005, 'error');
					}
					//释放优惠券
					$ordercode = $value['ordercode'];
					$map = [];
					$map['coupon_ordercode'] = $ordercode;
					$coupon_user = model('ErpCouponUseinfo') -> where($map) -> column('id');//当前订单使用的优惠券
					if(!empty($coupon_user)){
						foreach($coupon_user as $coupon_id){
							$map = [];
							$map['id'] = $coupon_id;
							
							$data = [];
							$data['coupon_ordercode'] = 0;
							$data['coupon_usetime'] = '';
							$data['coupon_use_type'] = 0;
							$rel = model('ErpCouponUseinfo')->update($data, $map);
							if(!$rel){
								DB::rollback();
								return array_out(-1005, 'error4');//退优惠券失败
							}
						}
					}
					
					$map = [];
					$map['order_id'] = $order_id;
					//释放库存
					$sku_list = model('ErpGoodsOrderSkulist') -> where($map) -> select();
					if(!empty($sku_list)){
						//根据门店id 查询出仓库的id
						$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($value['store_id']);
						$store_warehouse_list = [];
						foreach ($warehouse_list['data'] as $val) {
							if($val['type'] == 1){//分店仓库
								$store_warehouse_list[] = $val['wid'];
							}
						}
						$warehouse_id 	= $store_warehouse_list[0];//仓库id
			
						foreach($sku_list as $k => $v){
							$sku_id = $v['sku_id'];
							$num 	= $v['num'];
							$map = [];
							$map['sku_id'] 			= $sku_id;
							$map['warehouse_id'] 	= $warehouse_id;
							$sku_info = model('ErpGoodsWarehouseStockNum') -> where($map) -> find();//当前库存
							//计算库存数
							$frozen_num 	= $sku_info['frozen_num'] - $num; //冻结数 减少
							$available_num 	= $sku_info['available_num'] + $num; //可用库存增加
							$stock_num = $frozen_num + $available_num; //总库存
							
							
							// 插入库存
							$map = [];
							$map['id'] = $sku_info['id'];
							$map['warehouse_id'] = $warehouse_id;
							
							$data= [];
							$data['frozen_num'] 	= $frozen_num;
							$data['available_num'] 	= $available_num;
							$data['stock_num'] 		= $stock_num;
							$res = model('ErpGoodsWarehouseStockNum') -> update($data, $map);
							if(!$res){
								DB::rollback();
								return array_out(-1005, 'error2');
							}

							//判断是否是团购订单
							if($order_type ==1){
								$map = [];
								$map['id'] = $v['sponsor_id'];
								model('ErpGroupSponsorSku') ->where($map) -> setDec('dj_num', $v['num']);//冻结减去
							}
						}
					}else{
						DB::rollback();
						return array_out(-1005, 'error3');
					}
				}
			}
			DB::commit();
			return array_out(200, 'success');
		} catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}
	
}